package com.keda.service;

import com.keda.dao.UserDao;
import com.keda.model.User;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

public class UserService {

    public String login(String username, String password, String verifyCode,
                      HttpSession session) {

        // 1. 空值校验
        if (username == null || username.trim().isEmpty()) {
            return "请输入用户名";
        }
        if (password == null || password.trim().isEmpty()) {
            return "请输入密码";
        }
        if (verifyCode == null || verifyCode.trim().isEmpty()) {
            return "请输入验证码";
        }
        // 2. 验证码的准确性校验
        // 从session中读取
        String verifyCodeFromSession = (String)session
                .getAttribute("sRand");
        if (!verifyCode.equals(verifyCodeFromSession)) {
            return "验证码输入错误";
        }

        // 3. 查询数据库，根据用户名和密码
        UserDao userDao = new UserDao();

        User user = userDao.findByUsernamePassword(username.trim(), password);

        // 4. 判断是否有值
        if (user == null) {
            return "用户名或密码输入错误！";
        }

        // 5. 保存登录信息， 保存到Session
        session.setAttribute("currentUser", user);
        return "登录成功！";
    }

    public String register(String username, String password, String rePassWord,
                           String sex, String birthday, String dentityCode,
                           String email, String mobile, String address, HttpSession session) {
        // 1. 非空校验
        if (username == null || username.trim().isEmpty()) {
            return "请输入用户名";
        }
        if (password == null || password.trim().isEmpty()) {
            return "请输入密码";
        }
        if (rePassWord == null || rePassWord.trim().isEmpty()) {
            return "请输入重复密码";
        }
        if (!password.equals(rePassWord)) {
            return "两次密码不相同，请重新输入";
        }
        if (sex == null || sex.trim().isEmpty()) {
            return "请输入性别";
        }
        if (mobile == null || mobile.trim().isEmpty()) {
            return "请输入性别";
        }
        if (address == null || address.trim().isEmpty()) {
            return "请输入地址";
        }
        UserDao userDao = new UserDao();

        // 2. 用户名唯一
        User user = userDao.findByUsername(username.trim());
        if (user != null) {
            return "该用户名已存在，请重新输入";
        }
        // 3. 写入数据库

        Integer userId = userDao.insert(username, password,
                sex, birthday, dentityCode, email, mobile, address);
        user = new User();
        user.setId(userId);
        user.setUserName(username);
        // 4. 注册成功，那么自动登录
        session.setAttribute("currentUser", user);
        return "注册成功！";


    }
}
